//
//  LoginNumberViewController.m
//  day1
//
//  Created by 于跃隆 on 2020/4/5.
//  Copyright © 2020 于跃隆. All rights reserved.
//

#import "LoginNumberViewController.h"
#import <OpenInstallSDK.h>
#import "MyViewController.h"

@interface LoginNumberViewController ()<UITextFieldDelegate>
@property(nonatomic,strong) UITextField * inputNumberTextField;
@property(nonatomic,strong) UITextField * inputCodeTextField;
@property(nonatomic,strong) UITextField * yaoqingCodeTextField;
@property(nonatomic,strong) UIButton *codeBtn;
@property(nonatomic,strong) NSString *sessionID;
@property(nonatomic,strong) NSString *shareCode;

//导航渐变view
@property (nonatomic ,strong) UIView *Jbview;

@end

@implementation LoginNumberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //245 246 251
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:246/255.0 blue:251/255.0 alpha:1.0];
    //设置导航条颜色
        _Jbview = [[UIView alloc] init];
        _Jbview.userInteractionEnabled = YES;
    //    Jbview.frame = CGRectMake(0,KSCHEIGHT(-37),kSCRATIO(self.view.frame.size.width),KSCHEIGHT(75));

        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,KSCHEIGHT(0),kSCRATIO(self.view.frame.size.width),KSCHEIGHT(82));
        gl.startPoint = CGPointMake(0, 0);
        gl.endPoint = CGPointMake(1, 1);
        gl.colors = @[(__bridge id)[UIColor colorWithRed:247/255.0 green:65/255.0 blue:91/255.0 alpha:1.0].CGColor,(__bridge id)[UIColor colorWithRed:251/255.0 green:171/255.0 blue:102/255.0 alpha:1.0].CGColor];
        gl.locations = @[@(0.0),@(1.0)];
        [_Jbview.layer addSublayer:gl];
        
//        [self.navigationController.navigationBar addSubview:Jbview];
    [self.view addSubview:_Jbview];
        
        //返回button
        UIButton *backBtn = [[UIButton alloc] init];
        [backBtn setBackgroundImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(BackClick) forControlEvents:UIControlEventTouchUpInside];
        [_Jbview addSubview:backBtn];
        
        //标题文字
        UILabel *navtitle = [[UILabel alloc] init];
        navtitle.text = @"手机登录";
        navtitle.textColor = [UIColor whiteColor];
        navtitle.font = kFONT(18);
        [_Jbview addSubview:navtitle];
        
        [_Jbview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(KSCHEIGHT(0));
            make.width.mas_equalTo(kSCRATIO(self.view.frame.size.width));
            make.height.mas_equalTo(KSCHEIGHT(82));
        }];
        [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(_Jbview.mas_left).mas_equalTo(kSCRATIO(20));
            make.bottom.mas_equalTo(_Jbview.bottom).mas_equalTo(KSCHEIGHT(-15));
            make.width.mas_equalTo(kSCRATIO(10));
            make.height.mas_equalTo(KSCHEIGHT(18));
        }];
        [navtitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_Jbview);
            make.bottom.mas_equalTo(_Jbview.bottom).mas_equalTo(KSCHEIGHT(-15));
            
        }];
    
    
    self.shareCode=@"";
    [self setFrame];
    [[OpenInstallSDK defaultManager] getInstallParmsCompleted:^(OpeninstallData*_Nullable appData) {
        //在主线程中回调
        if (appData.data) {//(动态安装参数)
           //e.g.如免填邀请码建立邀请关系、自动加好友、自动进入某个群组或房间等
            if (![UtilTools isBlankString:appData.data[@"s"]]) {
                self.shareCode=appData.data[@"s"];
            }
        }
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    self.navigationController.navigationBar.hidden = YES;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    self.navigationController.navigationBar.hidden = NO;
}
-(void)setFrame{
    //站位view1
    UIView *whiteOneV = [[UIView alloc] init];
    whiteOneV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteOneV];
    //站位view2
    UIView *whiteTwoV = [[UIView alloc] init];
    whiteTwoV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteTwoV];
    //站位view3
    UIView *whiteThreeV = [[UIView alloc] init];
    whiteThreeV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteThreeV];
    
    
    self.inputNumberTextField = [[UITextField alloc] init];
    
    self.inputNumberTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.inputNumberTextField.delegate = self;
    self.inputNumberTextField.placeholder = @"请输入手机号";
    
    [whiteOneV addSubview:self.inputNumberTextField];
    [self.inputNumberTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(whiteOneV);
        make.centerY.mas_equalTo(whiteOneV);
        make.width.mas_equalTo(whiteOneV.width-kSCRATIO(30));
        make.left.mas_equalTo(kSCRATIO(30));
        make.right.mas_equalTo(kSCRATIO(0));
    }];
        
    self.inputCodeTextField.leftViewMode = UITextFieldViewModeAlways;
    
    [self.inputCodeTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.inputCodeTextField = [[UITextField alloc] init];
            self.inputCodeTextField.leftViewMode = UITextFieldViewModeAlways;
    
    [self.inputCodeTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.inputCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.inputCodeTextField.delegate = self;
    self.inputCodeTextField.placeholder = @"请输入验证码";
    [whiteTwoV addSubview:self.inputCodeTextField];
    
    [self.inputCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(whiteTwoV);
        make.centerY.mas_equalTo(whiteTwoV);
        make.width.mas_equalTo(whiteTwoV.width-kSCRATIO(30));
        make.left.mas_equalTo(kSCRATIO(30));
        make.right.mas_equalTo(kSCRATIO(0));
        
    }];
    
    
    //邀请码
    [self.yaoqingCodeTextField addTarget:self action:@selector(textFieldYQDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.yaoqingCodeTextField = [[UITextField alloc] init];
    self.yaoqingCodeTextField.leftViewMode = UITextFieldViewModeAlways;
    
    self.yaoqingCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.yaoqingCodeTextField.delegate = self;
    self.yaoqingCodeTextField.placeholder = @"请输入邀请码(非必填)";
    [whiteThreeV addSubview:self.yaoqingCodeTextField];
    
    [self.yaoqingCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(whiteThreeV);
        make.centerY.mas_equalTo(whiteThreeV);
        make.width.mas_equalTo(whiteThreeV.width-kSCRATIO(30));
        make.left.mas_equalTo(kSCRATIO(30));
        make.right.mas_equalTo(kSCRATIO(0));
        
    }];
    
    
    
    
    
    
    //获取验证码
    self.codeBtn  = [UIButton CreatButtontext:@"获取验证码" image:nil Font:[UIFont fontWithName:@"Helvetica-Bold" size:15.0] Textcolor:ColorWhite];
    [self.codeBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.codeBtn.backgroundColor = [UIColor colorWithRed:248/255.0 green:80/255.0 blue:92/255.0 alpha:1.0];
    self.codeBtn.layer.shadowColor = [UIColor colorWithRed:173/255.0 green:172/255.0 blue:172/255.0 alpha:0.14].CGColor;
    ViewRadius(self.codeBtn, KSCHEIGHT(30)/2);
    [whiteTwoV addSubview:self.codeBtn];
    
    
    //立即绑定按钮
    UIButton *loginButton = [[UIButton alloc] init];
    //设置渐变色
    
    CAGradientLayer *glT = [CAGradientLayer layer];
    glT.frame = CGRectMake(0,0,kSCRATIO(250),KSCHEIGHT(40));
    glT.startPoint = CGPointMake(0, 0);
    glT.endPoint = CGPointMake(1, 1);
    glT.colors = @[(__bridge id)[UIColor colorWithRed:247/255.0 green:65/255.0 blue:91/255.0 alpha:1.0].CGColor,(__bridge id)[UIColor colorWithRed:251/255.0 green:171/255.0 blue:102/255.0 alpha:1.0].CGColor];
    glT.locations = @[@(0.0),@(1.0)];
    ViewRadius(loginButton, KSCHEIGHT(20));

    [loginButton.layer addSublayer:glT];
    [loginButton setTitle:@"立即绑定" forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton.titleLabel setFont:[UIFont fontWithName:@"Microsoft YaHei" size:kSCRATIO(15)]];
    
    [self.view addSubview:loginButton];
    [loginButton addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(whiteThreeV.mas_bottom).mas_offset(KSCHEIGHT(40));
        make.width.mas_offset(kSCRATIO(250));
        make.height.mas_equalTo(KSCHEIGHT(40));
        make.centerX.mas_equalTo(self.view);
    }];
    
    
    
    //获取验证码约束
    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(whiteTwoV).mas_offset(kSCRATIO(KSCHEIGHT(-10)));
            make.height.mas_offset(KSCHEIGHT(30));
            make.width.mas_offset(kSCRATIO(100));
            make.right.mas_equalTo(whiteTwoV.mas_right).mas_equalTo(kSCRATIO(-20));
    }];
    
    
    
    
    //设置约束
    [whiteOneV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(_Jbview.mas_bottom).mas_equalTo(KSCHEIGHT(55));
//        make.width.mas_equalTo(kSCRATIO(self.view.frame.size.width));
        make.height.mas_equalTo(KSCHEIGHT(50));
        make.left.right.mas_equalTo(kSCRATIO(0));
    }];
    //设置约束
    [whiteTwoV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(whiteOneV.mas_bottom).mas_equalTo(KSCHEIGHT(55));
//        make.width.mas_equalTo(kSCRATIO(self.view.frame.size.width));
        make.height.mas_equalTo(KSCHEIGHT(50));
        make.left.right.mas_equalTo(kSCRATIO(0));
    }];
    //设置约束
    [whiteThreeV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(whiteTwoV.mas_bottom).mas_equalTo(KSCHEIGHT(55));
//        make.width.mas_equalTo(kSCRATIO(self.view.frame.size.width));
        make.height.mas_equalTo(KSCHEIGHT(50));
        make.left.right.mas_equalTo(kSCRATIO(0));
    }];
    
    
    
    
//    UIImageView *backImage = [[UIImageView alloc] init];
//    backImage.image = [UIImage imageNamed:@"loginBackImage"];
//    [self.view addSubview:backImage];
//    [backImage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_offset(0);
//        make.top.mas_offset(0);
//        make.height.mas_offset(KSCHEIGHT(299));
//    }];
//    UIView *view = [[UIView alloc] init];
//    view.backgroundColor = [UIColor whiteColor];
//    ViewRadius(view, 54);
//    [self.view addSubview:view];
//
//
//    [view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_offset(0);
//        make.top.mas_equalTo(backImage.mas_bottom).mas_offset(kSCRATIO(-54));
//        make.height.mas_offset(HEIGHT+100-KSCHEIGHT(299));
//    }];
//    UIButton* back=[UIButton buttonWithType:UIButtonTypeCustom];
//    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
//    [back addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:back];
//    [back mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).offset(kSCRATIO(34));
//        make.left.equalTo(self.view).offset(kSCRATIO(15));
//        make.width.height.mas_equalTo(kSCRATIO(44));
//    }];
//    UILabel *titLab = [UILabel CreatLabeltext:@"欢迎来到鲁班兼职" Font:[UIFont systemFontOfSize:20] Textcolor:ColorMain textAlignment:NSTextAlignmentLeft];
//    titLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.f];
//    [view addSubview:titLab];
//    [titLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(view.top).mas_offset(KSCHEIGHT(71));
//        make.left.mas_offset(50);
//    }];
//
//    UILabel *inputLab = [UILabel CreatLabeltext:@"请输入您的手机号码" Font:[UIFont fontWithName:@"Helvetica-Bold" size:15.0f] Textcolor:kColorFromRGBHex(0x333333) textAlignment:NSTextAlignmentLeft];
//    [view addSubview:inputLab];
//    [inputLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(titLab.mas_bottom).mas_offset(KSCHEIGHT(44));
//        make.left.mas_offset(50);
//    }];
//
//    UIView *line = [[UIView alloc] init];
//    line.backgroundColor = kColorFromRGBHex(0xE1E1E1);
//    [view addSubview:line];
//    [line mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(inputLab.mas_bottom).mas_offset(KSCHEIGHT(35.5));
//        make.left.mas_offset(50);
//        make.width.mas_offset(WIDTH-100);
//        make.height.mas_offset(1);
//    }];
//
//



//    UILabel *codeLab = [UILabel CreatLabeltext:@"请输入验证码" Font:[UIFont fontWithName:@"Helvetica-Bold" size:15.0f] Textcolor:kColorFromRGBHex(0x333333) textAlignment:NSTextAlignmentLeft];
//    [view addSubview:codeLab];
//    [codeLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(line).mas_offset(KSCHEIGHT(20));
//        make.left.mas_equalTo(line);
//    }];
//    UIView *lineView = [[UIView alloc] init];
//    lineView.backgroundColor = kColorFromRGBHex(0xE1E1E1);
//    [view addSubview:lineView];
//    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.width.height.right.mas_equalTo(line);
//        make.top.mas_equalTo(codeLab.mas_bottom).mas_offset(KSCHEIGHT(35.5));
//    }];
//

//
    
//    //取消第一响应者
//    [backImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(exitEdit)]];
//    [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(exitEdit)]];
}

-(void)exitEdit{
    [self.inputNumberTextField resignFirstResponder];
    [self.inputCodeTextField resignFirstResponder];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.inputNumberTextField resignFirstResponder];
    [self.inputCodeTextField resignFirstResponder];
}
#pragma --mark textfield delegate
//-(void)textViewDidChange:(UITextField *)textField{
//    if (textField== self.inputNumberTextField) {
//          if (textField.text.length >= 11) {
//              textField.text=[textField.text substringToIndex:11];
//
//          }
//      }
//
//      if (textField == self.inputCodeTextField){
//          if (textField.text.length >=4) {
//              textField.text=[textField.text substringToIndex:4];
//
//          }
//      }
//}
-(void)textFieldDidChange:(UITextField *)textField{
    if (textField == self.inputNumberTextField ) {
        if (textField.text.length>=11) {
            textField.text=[textField.text substringToIndex:11];
        }
    }
    if (textField == self.inputCodeTextField) {
        if (textField.text.length>=4) {
            textField.text=[textField.text substringToIndex:4];
        }
    }
    
}
//邀请码
-(void)textFieldYQDidChange:(UITextField *)textField{
    if (textField == self.inputNumberTextField ) {
        if (textField.text.length>=11) {
            textField.text=[textField.text substringToIndex:11];
        }
    }
    if (textField == self.inputCodeTextField) {
        if (textField.text.length>=4) {
            textField.text=[textField.text substringToIndex:4];
        }
    }
    
}
//验证码
-(void)btnClick:(UIButton *)sender{
    sender.enabled = NO;
    if ([UtilTools isBlankString:self.inputNumberTextField.text]) {
        [HWProgressHUD showMessage:@"手机号码为空"];
        sender.enabled = YES;
        return;
    }
    __weak typeof(self) weakSelf = self;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"86",@"nationcode",self.inputNumberTextField.text,@"mobile", nil];
    [[NetWorkManager sharedManager] postData:@"api/login/sendCode" parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToNumber:@200]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                sender.enabled = YES;
                [HWProgressHUD showMessage:@"发送成功"];
                [weakSelf sendtext];
                weakSelf.sessionID = responseObject[@"message"];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                sender.enabled = YES;
                [HWProgressHUD showMessage:responseObject[@"message"]];
                
            });
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        sender.enabled = YES;
        [HWProgressHUD showMessage:@"请联系管理员"];
        
        
    }];
}
-(void)sendtext{
    __block NSInteger second = 60;
    //全局队列    默认优先级
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式  事件源
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    
    
    //NSEC_PER_SEC是秒，＊1是每秒
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
    //设置响应dispatch源事件的block，在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(timer, ^{
        //回调主线程，在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second >0) {
                
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%ldS",(long)second] forState:UIControlStateNormal];
                
                self.codeBtn.enabled=NO;
                second--;
            }
            else
            {
                //这句话必须写否则会出问题
                dispatch_source_cancel(timer);
                [self.codeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                self.codeBtn.enabled=YES;
            }
        });
        
    });
    //启动源
    dispatch_resume(timer);
}
//登录
-(void)loginClick:(UIButton *)sender{
    sender.enabled = NO;
//    if ([UtilTools isBlankString:_inputNumberTextField.text]) {
//        sender.enabled = YES;
//        [HWProgressHUD showMessage:@"手机号为空"];
//        return;
//    }
//    if ([UtilTools isBlankString:_inputCodeTextField.text]) {
//        sender.enabled = YES;
//        [HWProgressHUD showMessage:@"验证码为空"];
//        return;
//    }
//    if ([UtilTools isBlankString:self.sessionID]) {
//        [HWProgressHUD showMessage:@"请重新发送验证码"];
//        sender.enabled = YES;
//        return;
//    }
//    NSDictionary *dic = @{@"mobile":_inputNumberTextField.text,
//                          @"code":_inputCodeTextField.text,
//                          @"sessionId":self.sessionID,
//    };
    NSDictionary *dic = @{@"mobile":_inputNumberTextField.text,
                             @"code":self.inputCodeTextField.text,
                          @"sessionId":[UtilTools isBlankString:self.sessionID]?@"11":self.sessionID,
                          @"user_type":@"iPhone",
                          @"edition":@"iPhone",
                          @"shareCode":self.shareCode,
       };
    __weak typeof(self) weakSelf = self;
    [[NetWorkManager sharedManager] postData:@"api/login/mobile" parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            //            dispatch_async(dispatch_get_main_queue(), ^{
            if (![UtilTools isBlankDictionary:responseObject[@"data"]]) {
                [OpenInstallSDK reportRegister];
            }
            [[NetWorkManager sharedManager] getData:@"api/user/info" parameters:@{
                @"token":responseObject[@"message"]
            } success:^(NSURLSessionDataTask *task, id responseObject) {
                if ([responseObject[@"code"] isEqualToNumber:@200]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        sender.enabled = YES;
                        [HWProgressHUD showMessage:@"登录成功"];
                        UserModel *user = [UserModel sharedInstance:UserKey0];
                        user.isLogin = YES;
                        user.nickName = weakSelf.inputNumberTextField.text;
                        user.token =responseObject[@"result"][@"cliToken"];
                        user.nickName = responseObject[@"result"][@"userName"];
                        user.personalSignature = responseObject[@"result"][@"userSignature"];
                        user.mobile = responseObject[@"result"][@"mobile"];
                        user.portrait = responseObject[@"result"][@"avatar"];
                        [UserModel saveData:UserKey0];
                        [[AppDelegate shareAppDelegate ] setupRootController];
                    });
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
            
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                sender.enabled = YES;
                [HWProgressHUD showMessage:responseObject[@"message"]];
            });
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            sender.enabled = YES;
            [HWProgressHUD showMessage:@"网络链接失败,请检查网络链接"];
        });
    }];
}

- (void)BackClick{
    
    UIViewController *viewController = self;
        if (viewController) {
            
            [viewController dismissViewControllerAnimated:NO completion:nil];
            [[AppDelegate shareAppDelegate ] setTabbarViewController];
        }
//    [self popoverPresentationController];
//    [self.navigationController popToViewController:[[MyViewController alloc] init] animated:YES];
//    [self.navigationController popViewControllerAnimated:YES];
}



@end
